
package com.lemon.cloud.log.event;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.lemon.cloud.admin.entity.SysLog;
import com.lemon.cloud.admin.feign.LogFeign;
import com.lemon.cloud.comm.constants.OAuth2Constant;
import com.lemon.cloud.log.config.LogProperties;
import com.lemon.cloud.log.entity.Log;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;

import java.util.Objects;

/**
 * @author 异步监听日志事件
 */
@Slf4j
@RequiredArgsConstructor
public class SysLogListener {

    private final LogFeign logFeign;

    private final LogProperties logProperties;

    @Order
    @EventListener(SysLogEvent.class)
    public void saveSysLog(SysLogEvent event) {
        try {
            Log log = (Log) event.getSource();
            // json 格式刷参数放在异步中处理，提升性能
            if (Objects.nonNull(log.getParams())) {
                log.setParams(StrUtil.subPre(log.getParams(), logProperties.getMaxLength()));
            }
            SysLog sysLog = new SysLog();
            BeanUtil.copyProperties(log,sysLog,logProperties.getExcludeFields().toArray(new String[0]));
            logFeign.saveLog(sysLog, OAuth2Constant.FROM_IN);
        } catch (Exception e) {
            log.error("异常：异步监听日志事件，{}", e.getMessage());
        }
    }


}
